import React, { Component, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Form, Card, Select, List, Icon, Row, Col, Button,Tooltip,Modal } from 'antd';

import Ellipsis from 'components/Ellipsis';
import StandardFormRow from 'components/StandardFormRow';
import styles from './List.less';

import { fetchPost } from '../../utils/utils';
import host from '../../services/host';
import {getAuthToken} from '../../utils/authority';

const { Option } = Select;
const FormItem = Form.Item;
const confirm = Modal.confirm;

const pageSize = 8;

@Form.create()
@connect(({ article, loading }) => ({
  list: article.list,
  authors: article.authors,
  loading: loading.models.list,
  checkLoading:loading.effects['article/check'],
  publoading: loading.effects['article/pubArticle'],
  cancelPubloading: loading.effects['article/cancelPubArticle'],
}))
export default class ArticleList extends Component {
  state = {
    page:1,
    visible: false,
    checkItem:{
      title:'',
      content:'',
      id:'',
      cover:'',
    },
  };
  componentDidMount() {
    this.fetchAuthor();
    this.fetchMore();
  };
  setOwner = () => {
    const { form } = this.props;
    form.setFieldsValue({
      owner: ['wzj'],
    });
  };
  fetchAuthor = () => {
      this.props.dispatch({
        type: 'article/fetchAuthor',
        payload:{},
      });
  };
  fetchMore = () => {
    if(this.state.page === 1){
      this.props.dispatch({
        type: 'article/fetch',
        payload: {
          count: pageSize,
          page:this.state.page,
        },
      });
    }else{
      this.props.dispatch({
        type: 'article/appendFetch',
        payload: {
          count: pageSize,
          page:this.state.page,
        },
      });
    }
    this.setState({
      page:this.state.page + 1,
    });
  };

  pubArticle = (id) => {
    this.props.dispatch({
      type: 'article/pubArticle',
      payload: {
        article_id : id,
      },
    });
  };
  cancelPubArticle = (id) => {
    this.props.dispatch({
      type: 'article/cancelPubArticle',
      payload: {
        article_id : id,
      },
    });
  };

  handleDelete = (id) =>{
    const my = this;
    const list = my.props.list;
    confirm({
      title: '确定要删除该文章?',
      content: '如果这个文章已经发布到APP了，删除之后APP将不再显示',
      okText:"删除",
      cancelText:"取消",
      onOk() {
        return new Promise((resolve, reject) => {
          fetchPost(`${host.host}/bearadmin/article/delete`, {id:id, authToken:getAuthToken()}, (error, response) => {
            console.log(response);
            if(error === null){
              for (let i = 0; i < list.length; i++) {
                if(list[i].id === id){
                  list.splice(i,1);
                }
              }
              my.props.dispatch({
                type:'article/updateListData',
                payload:list,
              });
              resolve();
            }else{
              reject();
            }
          });
        }).catch(() => console.log('Oops errors!'));
      },
      onCancel() {},
    });
  };

  handleSubCheck = (id) => {
    this.props.dispatch({
      type: 'article/subCheck',
      payload: {
        article_id:id,
      },
    });
  };
  handleCheck = (item) => {
    // const my = this;
    this.setState({
      visible: true,
      checkItem:{...item},
    });
  };
  handleAdopt = (id) =>{
    this.props.dispatch({
      type: 'article/check',
      payload: {
        article_id:id,
        status: 3,
      },
    });
  };
  handleNotThrough = (id) => {
    this.props.dispatch({
      type: 'article/check',
      payload: {
        article_id:id,
        status: 4,
      },
    });
  };

  handleCheckOk = () =>{
    this.setState({
      visible: false,
    });
  };

  handleCheckCancel = () =>{
    this.setState({
      visible: false,
    });
  };

  handleSetting = (item) => {
    console.log(item);
  };

  getStatusMsg = (item) =>{
    switch (item.status){
      case 1: return '编辑中';
      case 2: return <span style={{color:'#0084FF'}}>待审核</span>;
      case 3:
          if(item.online === 1){
            return '已发布';
          }else{
            return <span style={{color:'#0EFF31'}}>审核通过,未发布</span>;
          }
      case 4: return <span style={{color:'#f00'}}>审核不通过</span>;
      default: return <span style={{color:'#FFF80C'}}>未知状态</span>;
    }
  };

  render() {
    const { form, list, authors, loading, checkLoading,publoading, cancelPubloading } = this.props;
    const { getFieldDecorator } = form;

    const loadMore =
      list.length > 0 ? (
        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <Button onClick={this.fetchMore} style={{ paddingLeft: 48, paddingRight: 48 }}>
            {loading ? (
              <span>
						    <Icon type="loading" /> 加载中...
						  </span>
            ) : (
              '加载更多'
            )}
          </Button>
        </div>
      ) : null;

    const actions = (item) => {
      // 文章状态;1编辑中,2完成待审核,3审核通过,4审核不通过
      const action = [];
      action.push(
        <Tooltip title="设置">
          <Icon type="setting" onClick={() => this.handleSetting(item)}/>
        </Tooltip>,
      );
      if(item.status === 1 || item.status === 4){
        action.push(
          <a title="修改文章" href={`#/article/pub-article?id=${item.id}`}>
            <Icon type="edit"/>
          </a>,
          <div onClick={() => this.handleDelete(item.id)} title="删除该文章">
            <Icon type="delete" />
          </div>,
          <Tooltip title="提交审核">
            <Icon type="save" onClick={() => this.handleSubCheck(item.id)}/>
          </Tooltip>,
          <Tooltip title="审核">
            <Icon type="check" onClick={() => this.handleCheck(item)}/>
          </Tooltip>,
        );
      }else if(item.status === 2){
        action.push(
          <Tooltip title="审核">
            <Icon type="check" onClick={() => this.handleCheck(item)}/>
          </Tooltip>,
        );
      }else if(item.status === 3 && item.online === 0){
        action.push(
          <Button style={{height:23}} loading={publoading} size="small" onClick={() => {this.pubArticle(item.id)}}>
            发布
          </Button>
        )
      }else{
        action.push(
          <Button style={{height:23}} loading={cancelPubloading} onClick={() => {this.cancelPubArticle(item.id)}}>
            撤销发布
          </Button>
        )
      }
      return action;
    };
    return (
      <Fragment>
        <Modal
          title={this.state.checkItem.title}
          visible={this.state.visible}
          footer={null}
          onOk={this.handleCheckOk}
          onCancel={this.handleCheckCancel}
        >
          <img style={{width:'100%'}} src={this.state.checkItem.cover} alt={this.state.checkItem.title}/>
          <div dangerouslySetInnerHTML={{__html: this.state.checkItem.content}} />
          <Row style={{textAlign:'center',marginTop:50}}>
            <Button loading={checkLoading} style={{marginLeft:20}} onClick={() => this.handleAdopt(this.state.checkItem.id)} type="primary" size="large" icon="check">审核通过</Button>
            <Button loading={checkLoading} style={{marginLeft:20}} onClick={() => this.handleNotThrough(this.state.checkItem.id)} type="default" size="large" icon="close">审核不通过</Button>
          </Row>
        </Modal>
        <Card bordered={false}>
          <Form layout="inline">
            <StandardFormRow title="作者" grid>
              <Row>
                <Col lg={16} md={24} sm={24} xs={24}>
                  <FormItem>
                    {getFieldDecorator('owner', {
                      initialValue: [],
                    })(
                      <Select
                        mode="multiple"
                        style={{ maxWidth: 286, minWidth: 100 }}
                        placeholder="选择作者"
                      >
                        {authors.map(author => (
                          <Option key={author.id} value={author.id}>
                            {author.nickname}
                          </Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </StandardFormRow>
          </Form>
        </Card>
        <div className={styles.coverCardList}>
          <List
            size="large"
            loading={list.length === 0 ? loading : false}
            rowKey="id"
            grid={{ gutter: 24, column:4 }}
            loadMore={loadMore}
            dataSource={list}
            renderItem={item => (
              <List.Item>
                <Card
                  hoverable
                  className={styles.card}
                  cover={<img alt={item.title} src={item.cover} />}
                  actions={actions(item)}
                >
                  <Card.Meta
                    title={item.title}
                    description={<Ellipsis lines={2}>{item.intro}</Ellipsis>}
                  />
                  <div className={styles.cardItemContent}>
                    <span>{item.author}</span>
                    <span>{moment(item.create_time).fromNow()}</span>
                    <span>{this.getStatusMsg(item)}</span>
                  </div>
                </Card>
              </List.Item>
            )}
          />
        </div>
      </Fragment>
    );
  }
}
